package com.lucky.apple.test;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Created by he on 2018/5/18.
 */
public class singleDown {

    private static Logger logger = LoggerFactory.getLogger(singleDown.class);

    public static void startDownLoad(){
        logger.info("下载开始");
        long startTime = System.currentTimeMillis();
        String url = "http://download.oracle.com/otn-pub/java/jdk/8u171-b11-demos/512cd62ec5174c3487ac17c61aaa89e8/jdk-8u171-solaris-sparcv9-demos.tar.Z?AuthParam=1526628815_c04be0565009f8d07894468f740e9e3d";
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            long length = entity.getContentLength();
            logger.info("下载文件总共: "+(length/1024)/1024 +"MB");
            FileOutputStream stream = new FileOutputStream("D:\\work\\personal\\httpdown\\jdk2");
            BufferedOutputStream out = new BufferedOutputStream(stream);
            BufferedInputStream in = new BufferedInputStream(entity.getContent());
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = in.read(b)) > 0) {
                out.write(b,0,len);
            }
            logger.info("下载完成:" + (System.currentTimeMillis() - startTime) +"ms");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
}
